package matrix;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @className: Leetcode_123
 * @Description: ...
 * @author: kunkun
 * @date: 2025/3/19 20:59
 */
public class LeetCode_54 {

    @Test
    public void test(){
        List<Integer> list = spiralOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
        for (Integer integer : list) {
            System.out.print(integer+" ");
        }
    }

    public List<Integer> spiralOrder(int[][] matrix) {
        //1. 初始化坐标，访问矩阵，方向
        int i=0,j=0,count=0;
        int[][] flag = new int[matrix.length][matrix[0].length];
        List<Integer> list = new ArrayList<>();

        //2. 循环打印
        while (true){
            //2.1 遍历打印
            boolean temp = true;
            while (i>=0 && j>=0 && j<matrix[0].length && i< matrix.length && flag[i][j]==0 ){
                temp = false;
                list.add(matrix[i][j]);
                flag[i][j]=1;
                if (count%4==0){
                    j++;
                } else if (count%4==1) {
                    i++;
                } else if (count%4==2) {
                    j--;
                }else if (count%4==3){
                    i--;
                }
            }
            //2.2 跳出循环，无路可走
            if (temp){
                break;
            }
            //2.3 返回，并转向
            if (count%4==0){
                j--;
                i++;
            } else if (count%4==1) {
                i--;
                j--;
            } else if (count%4==2) {
                j++;
                i--;
            }else if (count%4==3){
                i++;
                j++;
            }
            count++;
        }
        return list;

    }
}
